from urllib.parse import urlencode

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from meiduo_mall.settings.dev import logger
from .models import User


def get_user_by_account(account):
    try:
        if re.match('^1[345789]\d{9}$', account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        logger.error('用户对象不存在')
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的username获取user对象。username可以是手机号也可以是账号

        # 区分前台还是后台再调用登录
        # if 'meiduo_admin/' in request.path:
        #     # 后台
        #     pass
        # else:
        #     # 前台
        #     pass

        if request is None:
            # 后台：jwt调用时未传递request对象
            try:
                # 查询指定用户名，并且是管理员
                user = User.objects.get(username=username, is_staff=True)
            except:
                return None
            else:
                # 判断密码是否正确
                if user.check_password(password):
                    return user
                else:
                    return None
        else:
            # 前台：调用时传递request对象

            user = get_user_by_account(username)

            # 校验user是否存在并校验密码是否正确
            if user and user.check_password(password):
                return user
            else:
                return None


# 封装生成激活链接的函数
def generate_verify_email_url(user):
    host_url = settings.EMAIL_ACTIVE_URL
    data_dict = {
        'user_id': user.id,
        'email': user.email
    }
    verify_url = host_url + '?' + urlencode(data_dict)

    return verify_url
